package com.xywl.escort.view.user.register;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.CaptchaBean;
import com.xywl.escort.bean.GetSmsCodeReq;
import com.xywl.escort.bean.RegisterReq;
import com.xywl.escort.common.Constant;
import com.xywl.escort.net.BaseSubscriber;
import com.xywl.escort.net.ExceptionHandle;
import com.xywl.escort.net.api.service.ApiServer;
import com.xywl.escort.utils.RxUtil;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.IOException;

import javax.inject.Inject;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by 32422 on 2017/10/25.
 */

public class RegisterPresenter implements RegisterContract.Presenter {
    private RegisterContract.View mView;
    private ApiServer mApiServer;

    @Inject
    RegisterPresenter(ApiServer apiServer) {
        mApiServer = apiServer;
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unSubscribe() {
        mView = null;
    }

    @Override
    public void takeView(RegisterContract.View view) {
        this.mView = view;
    }

    @Override
    public void getCode(GetSmsCodeReq req) {
        mApiServer.getSmsCode(req)
                .compose(RxUtil.<BaseResp>applySchedulers(RxUtil.IO_ON_UI_TRANSFORMER_BACK_PRESSURE))
                .compose(mView.<BaseResp>bindToLife())
                .subscribe(new BaseSubscriber<BaseResp>() {
                    @Override
                    protected void hideDialog() {

                    }

                    @Override
                    protected void showDialog() {

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        mView.getCodeFailure("");
                    }

                    @Override
                    public void onNext(BaseResp resp) {
                        if (null != resp && resp.isOk()) {
                            mView.startCountDown();
                        } else {
                            if (null != resp) {
                                mView.getCodeFailure(resp.msg);
                            } else {
                                mView.getCodeFailure("");
                            }
                        }
                    }
                });
    }

    @Override
    public void register(RegisterReq req) {
        mApiServer.register(req)
                .compose(RxUtil.<BaseResp>applySchedulers(RxUtil.IO_ON_UI_TRANSFORMER_BACK_PRESSURE))
                .compose(mView.<BaseResp>bindToLife())
                .subscribe(new BaseSubscriber<BaseResp>() {
                    @Override
                    protected void hideDialog() {

                    }

                    @Override
                    protected void showDialog() {

                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {
                        mView.registerFailure("");
                    }

                    @Override
                    public void onNext(BaseResp resp) {
                        if (null != resp) {
                            if (resp.isOk()) {
                                mView.registerSuccess(resp);
                            } else {
                                mView.registerFailure(resp.msg);
                            }
                        } else {
                            mView.registerFailure("");
                        }
                    }
                });
    }

    @Override
    public void getCaptcha() {
        Flowable.create(new FlowableOnSubscribe<CaptchaBean>() {
            @Override
            public void subscribe(FlowableEmitter<CaptchaBean> subscriber) {
                OkHttpClient client = new OkHttpClient();
                final RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{}");
                final Request request = new Request.Builder().url(Constant.Url.API_SERVER_URL + "api/user/user/getCaptcha").post(requestBody).build();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String captchaKey = response.header("captchaKey");
                        byte[] byte_image = response.body().bytes();
                        Bitmap bitmap = BitmapFactory.decodeByteArray(byte_image, 0, byte_image.length);
                        CaptchaBean bean = new CaptchaBean();
                        bean.bitmap = bitmap;
                        bean.captchaKey = captchaKey;
                        subscriber.onNext(bean);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
                subscriber.onComplete();
            }
        }, BackpressureStrategy.BUFFER)
                .compose(RxUtil.<CaptchaBean>applySchedulers(RxUtil.IO_ON_UI_TRANSFORMER_BACK_PRESSURE))
                .compose(mView.<CaptchaBean>bindToLife())
                .subscribe(new Subscriber<CaptchaBean>() {
                    @Override
                    public void onSubscribe(Subscription s) {//响应式拉取数据
                        s.request(Long.MAX_VALUE);
                    }

                    @Override
                    public void onNext(CaptchaBean bean) {
                        mView.getCaptchaSuccess(bean);
                    }

                    @Override
                    public void onError(Throwable t) {
                        mView.getCaptchaFailure();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}
